package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.data.core.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.eduBusiEnrollOrder.EduBusiEnrollOrderQueryVO;
import com.jwsoft.manager.common.vo.eduHouseholdOffline.EduHouseholdOfflineVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.EduSocialSecurityService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollPreService;
import com.jwsoft.manager.core.integration.EduBusiEnrollOrderIntegration;
import com.jwsoft.manager.core.integration.EduSocialSecurityIntegration;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduSocialSecurityOffline.EduSocialSecurityOfflineVO;
import com.jwsoft.manager.common.vo.eduSocialSecurityOffline.EduSocialSecurityOfflineKeyVO;
import com.jwsoft.manager.common.vo.eduSocialSecurityOffline.EduSocialSecurityOfflineQueryVO;
import com.jwsoft.manager.core.integration.EduSocialSecurityOfflineIntegration;
import com.jwsoft.manager.core.dao.service.EduSocialSecurityOfflineService;

/**
 * 线下社保新增业务实现类
 *
 * @author wangt
 * @since 2024-06-06
 */
@ApiService(funcCode = "eduSocialSecurityOffline", title = "线下社保新增")
public class EduSocialSecurityOfflineIntegrationImpl implements EduSocialSecurityOfflineIntegration {

    @Autowired
    public EduSocialSecurityOfflineService eduSocialSecurityOfflineService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduSocialSecurityService eduSocialSecurityService;

    @Autowired
    private EduBusiEnrollOrderIntegration eduBusiEnrollOrderIntegration;

    @Autowired
    private EduSocialSecurityIntegration eduSocialSecurityIntegration;

    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;

    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0001", title = "线下社保新增分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSocialSecurityOfflineVO> getList(EduSocialSecurityOfflineQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduSocialSecurityOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getAuthStatus()),EduSocialSecurityOffline::getAuthStatus,vo.getAuthStatus())
                .eq(StringUtils.isNotBlank(vo.getAac147()),EduSocialSecurityOffline::getAac147,vo.getAac147());

        List<EduSocialSecurityOffline> list = eduSocialSecurityOfflineService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSocialSecurityOffline> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSocialSecurityOfflineVO> resultList = Convert.toList(EduSocialSecurityOfflineVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0002", title = "线下社保新增根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduSocialSecurityOfflineVO getById(EduSocialSecurityOfflineKeyVO vo) {
        EduSocialSecurityOffline entity = eduSocialSecurityOfflineService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSocialSecurityOfflineVO result = Convert.convert(EduSocialSecurityOfflineVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0003", title = "线下社保新增保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSocialSecurityOfflineVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0004", title = "线下社保新增新增", funcType = FuncTypeEnum.insert,publicFlag = BoolEnum.TRUE)
    @SaveOplog(
            operationType = "eduSocialSecurityOffline0004",
            operationName = "线下社保新增新增",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSocialSecurityOfflineVO add(EduSocialSecurityOfflineVO vo) {
        Integer year = eduHelper.thisYear();
        vo.setYear(year);
        //保存前校验
        checkSave(vo);

        QueryWrapper<EduSocialSecurity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSocialSecurity::getAac147,vo.getIdcard());
        List<EduSocialSecurity> enrollPreList = eduSocialSecurityService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(enrollPreList)){
            throw new AppException(vo.getIdcard()+"该身份证已办理社保登记！");
        }

        QueryWrapper<EduSocialSecurityOffline> queryWrapperOffline = new QueryWrapper<>();
        queryWrapperOffline.lambda().eq(EduSocialSecurityOffline::getAac147,vo.getIdcard());
        List<EduSocialSecurityOffline> enrollPreOfflineList = eduSocialSecurityOfflineService.list(queryWrapperOffline);
        if(!CollectionUtils.isEmpty(enrollPreOfflineList)){
            throw new AppException(vo.getIdcard()+"该身份证已办理线下社保登记，请不要重复登记！");
        }


        vo.setAuthStatus(AuthStatusEnum.NODO.getType());
        vo.setAae140("110");

        //保存数据
        EduSocialSecurityOffline entity = Convert.convert(EduSocialSecurityOffline.class, vo);
        eduSocialSecurityOfflineService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setSocialSecurityId(entity.getSocialSecurityId());


        EduBusiEnrollOrderQueryVO orderQueryVO = new EduBusiEnrollOrderQueryVO();
        orderQueryVO = Convert.convert(EduBusiEnrollOrderQueryVO.class, vo);
        orderQueryVO.setFullName(vo.getAac003());
        String orderNum = eduBusiEnrollOrderIntegration.appDistributeOrderNum(orderQueryVO);
        vo.setOrderNum(orderNum);

        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0005", title = "线下社保新增修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSocialSecurityOffline0005",
            operationName = "线下社保新增修改",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSocialSecurityOfflineVO edit(EduSocialSecurityOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getSocialSecurityId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSocialSecurityOffline oldEntity = eduSocialSecurityOfflineService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSocialSecurityOffline entity = Convert.convert(EduSocialSecurityOffline.class, vo);
        eduSocialSecurityOfflineService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0006", title = "线下社保新增根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSocialSecurityOffline0006",
            operationName = "线下社保新增删除",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSocialSecurityOfflineKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getSocialSecurityId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSocialSecurityOffline entity = eduSocialSecurityOfflineService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSocialSecurityOfflineService.removeById(vo.getSocialSecurityId());
    }

    @Override
    @OpApi(funcCode = "eduSocialSecurityOffline0010", title = "线下社保登记保存", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSocialSecurityOffline0010",
            operationName = "线下社保登记保存",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSocialSecurityVO saveOffline(EduSocialSecurityOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getSocialSecurityId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSocialSecurityOffline oldEntity = eduSocialSecurityOfflineService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }


        //保存数据
        oldEntity.setAuthStatus(vo.getAuthStatus());
        eduSocialSecurityOfflineService.updateById(oldEntity);


        if(AuthStatusEnum.YES.getType().equals(vo.getAuthStatus())){
            EduSocialSecurityVO socialSecurityVO = Convert.convert(EduSocialSecurityVO.class,oldEntity);
            clearCache(socialSecurityVO.getAac147());
            eduSocialSecurityIntegration.add(socialSecurityVO);
            return socialSecurityVO;
        }else {
            return null;
        }
    }

    //清除缓存
    private void clearCache(String idcard){
        //查询人员
        if(StringUtils.isBlank(idcard)){
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            //社保
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
}
